package com.witmore.skyline.web.service.third.aliyun;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.facebody20191230.Client;
import com.aliyun.facebody20191230.models.DetectPedestrianAdvanceRequest;
import com.aliyun.facebody20191230.models.DetectPedestrianResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.jk.aliyun.oss.OssProperties;
import com.witmore.skyline.web.service.third.aliyun.dto.PedestrianDetectionResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 阿里云人体检测服务 - 使用AdvanceRequest方式支持非上海地域OSS
 *
 * @author 豆子高
 * @date 2025-01-01
 */
@Slf4j
@Service
public class AliyunPedestrianDetectionService {


    @Autowired
    private OssProperties ossProperties;
    /**
     * 阿里云视觉智能开放平台的endpoint
     */
    private static final String ENDPOINT = "facebody.cn-shanghai.aliyuncs.com";

    /**
     * 人体检测 - 使用AdvanceRequest方式支持非上海地域OSS
     *
     * @param imageUrl 图片URL地址
     * @return 检测结果
     */
    public PedestrianDetectionResult detectPedestrian(String imageUrl) {
        PedestrianDetectionResult result = new PedestrianDetectionResult();
        result.setHasHuman(false);
        result.setHumanCount(0);

        try {
            // 配置阿里云客户端
            Config config = new Config()
                    .setAccessKeyId(ossProperties.getAccessKeyId())
                    .setAccessKeySecret(ossProperties.getAccessKeySecret())
                    .setEndpoint(ENDPOINT);

            Client client = new Client(config);

            // 使用URL获取输入流（适用于非上海地域OSS或任意可访问的URL）
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openConnection().getInputStream();

            // 构建AdvanceRequest请求
            DetectPedestrianAdvanceRequest request = new DetectPedestrianAdvanceRequest()
                    .setImageURLObject(inputStream);

            RuntimeOptions runtime = new RuntimeOptions();

            // 调用API（使用detectPedestrianAdvance方法）
            DetectPedestrianResponse response = client.detectPedestrianAdvance(request, runtime);
            log.info("阿里云人体检测状态码：{},结果：{}", response == null ? "null" : response.getStatusCode(), response == null ? "null" : JSONObject.toJSONString(response.getBody()));
            if (response != null && response.getBody() != null && response.getStatusCode() == 200) {
                var body = response.getBody();
                result.setRequestId(body.getRequestId());

                if (body.getData() != null) {
                    result.setWidth(body.getData().getWidth());
                    result.setHeight(body.getData().getHeight());

                    var elements = body.getData().getElements();

                    if (!CollectionUtils.isEmpty(elements)) {
                        result.setHasHuman(true);
                        result.setHumanCount(elements.size());

                        List<PedestrianDetectionResult.DetectionElement> resultElements = new ArrayList<>();
                        for (var element : elements) {
                            PedestrianDetectionResult.DetectionElement detectionElement =
                                    new PedestrianDetectionResult.DetectionElement();
                            detectionElement.setType(element.getType());
                            detectionElement.setBoxes(element.getBoxes());
                            detectionElement.setScore(element.getScore());
                            resultElements.add(detectionElement);
                        }
                        result.setElements(resultElements);
                    }
                }
            }

            // 关闭输入流
            inputStream.close();

            log.info("阿里云人体检测完成，图片URL：{}，检测到人体：{}，人体数量：{}",
                    imageUrl, result.isHasHuman(), result.getHumanCount());

        } catch (Exception e) {
            log.error("阿里云人体检测失败，图片URL：{}，错误信息：{}", imageUrl, e.getMessage(), e);
        }

        return result;
    }
}
